#!/usr/bin/env python3
# DATA: 2023/9/2
# author: 
#
import os.path
import socket
import logging
from flask import Flask, request
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(funcName)s %(lineno)d %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S', filename="TransLAN.log", filemode="w")
app = Flask(__name__)


def get_local_ip_address():
    """ 获取本地ip地址 """
    countip = socket.getaddrinfo(socket.gethostname(), None, family=socket.AF_INET, proto=socket.IPPROTO_TCP)
    ipaddr = ""
    for i in range(len(countip)):
        ips = i, socket.getaddrinfo(socket.gethostname(), None, family=socket.AF_INET, proto=socket.IPPROTO_TCP)[i][4][
            0]
        if str(ips[1]).split(".")[-1] != '1':
            ipaddr = ips[1]
    logging.info(f"机器的ip地址为：{ipaddr}")
    return ipaddr


@app.route("/receive/file", methods=['POST'])
def receive_file():
    savepath = os.path.join(os.getcwd(), 'files')
    if os.path.exists(savepath) is False:
        os.makedirs(savepath)
    try:
        file = request.files['file']
        filename = file.filename
        savepath = os.path.join(savepath, filename)
        file.save(savepath)
        logging.info(f"上传成功，文件保存在{savepath}")
        return {"status": "success", "msg": f"上传成功，文件保存在{savepath}"}
    except Exception as e:
        logging.error(f'操作失败，{e}')
        return {"status": "fail", "msg": e}


if __name__ == '__main__':
    if not os.popen("netstat -an |findstr 8400").readlines():
        ipaddr = get_local_ip_address()
        app.run(host=ipaddr, port=8400)
